/*
 * @lc app=leetcode.cn id=605 lang=javascript
 *
 * [605] 种花问题
 */

// @lc code=start
/**
 * @param {number[]} flowerbed
 * @param {number} n
 * @return {boolean}
 */
var canPlaceFlowers = function (flowerbed, n) {
  const size = flowerbed.length;
  let count = 0;
  // 上一朵花的索引
  let prev = -1;
  let i = -1;
  while (++i < size) {
    if (flowerbed[i] === 1) {
      if (prev < 0) {
        // 0-花
        count += (i - 0) >> 1;
      } else {
        // 花-花 j-i-1-1
        count += (i - prev - 2) >> 1;
      }
      prev = i;
      if (count >= n) return true;
    }
  }
  if (prev < 0) {
    count += (size + 1) >> 1;
  } else {
    count += (size - prev - 1) >> 1;
  }

  return count >= n;
};
// @lc code=end
